﻿Imports System.IO
Imports System.Text
Imports Interop.SVault.Client.SDK

Public Class ToolbarForm
    Private Const OurClientId = "SampleCRMWinClient"
    Private Const OurApplicationId = "SampleCRM"

    Private _dirty As Boolean
    Private _hasName As Boolean
    Private _filename As String

    Private _editItem As CustomerRecord
    Private _newItemInfo As Interop.SVault.Client.SDK.IContextNewItem

    Private _guid As Guid
    Private _nextCustomerId As Integer

    Private _Toolbar
    Private _Context As Interop.SVault.Client.SDK.IApplicationContext

    Public Sub New(ByVal filename As String, ByVal hasname As Boolean)
        InitializeComponent()

        SetFileName(filename)
        _hasName = hasname

        If hasname Then
            Read()
        Else
            _guid = Guid.NewGuid()
            _dirty = True
            _nextCustomerId = 1
        End If

    End Sub

    Private Sub ChildForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        _Toolbar = Activator.CreateInstance(Type.GetTypeFromProgID("SmartVault.Toolbar.1"))
        _Toolbar.Dock = System.Windows.Forms.DockStyle.Right
        _Toolbar.Location = New System.Drawing.Point(626, 0)
        _Toolbar.Margin = New System.Windows.Forms.Padding(0)
        _Toolbar.MaximumSize = New System.Drawing.Size(58, 9999)
        _Toolbar.MinimumSize = New System.Drawing.Size(58, 50)
        _Toolbar.Name = "Toolbar"
        _Toolbar.Size = New System.Drawing.Size(58, 406)
        _Toolbar.TabIndex = 0
        Me.Controls.Add(_Toolbar)
    End Sub

    Private Sub ToolbarForm_Shown(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Shown
        _Toolbar.Unlock(OurClientId)
        _Context = _Toolbar.OpenToolbar(OurApplicationId, _guid.ToString(), Path.GetFileName(_filename))

        SetNewItem()
    End Sub

    Public ReadOnly Property HasName() As Boolean
        Get
            Return _hasName
        End Get
    End Property

    Public ReadOnly Property FileName() As String
        Get
            Return _filename
        End Get
    End Property

    Private Sub SetFileName(ByVal value As String)
        _hasName = True
        _filename = value
        Me.Text = Path.GetFileName(_filename)
    End Sub

    Private Sub Read()

        Using s As New FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.Read, 1024)
            Using rdr As New StreamReader(s, Encoding.UTF8)
                _guid = New Guid(rdr.ReadLine())

                Dim count = Integer.Parse(rdr.ReadLine())
                For i As Integer = 1 To count
                    Dim tmp As New CustomerRecord
                    If tmp.Read(rdr) Then
                        Me.CustomerList.Items.Add(tmp)
                        _nextCustomerId = Math.Max(_nextCustomerId, tmp.Id + 1)
                    Else
                        Exit For
                    End If
                Next
            End Using
        End Using

        _dirty = False
    End Sub

    Public Sub Save()
        _dirty = False

        Using s As New FileStream(_filename, FileMode.Create, FileAccess.Write, FileShare.Read, 1024)
            Using wtr As New StreamWriter(s, Encoding.UTF8)
                wtr.WriteLine(_guid)
                wtr.WriteLine(CustomerList.Items.Count)
                For Each cust As CustomerRecord In CustomerList.Items
                    cust.Write(wtr)
                Next
            End Using
        End Using

    End Sub

    Public Sub SaveAs(ByVal value As String)
        SetFileName(value)
        Save()
    End Sub

    Private Sub ToolbarForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        If _dirty And _hasName Then

            Dim response As DialogResult
            response = MessageBox.Show("The file has been modified, Save changes?", "Save Changes?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button3)

            If response = DialogResult.Cancel Then
                e.Cancel = True
            ElseIf response = Windows.Forms.DialogResult.Yes Then
                Save()
            End If
        End If
    End Sub

    Private Sub SetNewItem()
        Dim customer As New CustomerRecord
        EditItem(True, customer)
    End Sub

    Private Sub SetExistingItem(ByVal customer As CustomerRecord)
        EditItem(False, customer)
    End Sub

    Private Sub SetNoneItem()
        If Not (_newItemInfo Is Nothing) Then
            _Context.ClearCurrentItem()
            _newItemInfo.AbandonItem()
            _newItemInfo = Nothing
        End If

        CustomerList.SelectedItems.Clear()
        _editItem = Nothing
        FirstNameTxt.Text = String.Empty
        LastNameTxt.Text = String.Empty
        CustomerIdTxt.Text = String.Empty
        FirstNameTxt.Enabled = False
        LastNameTxt.Enabled = False
        Customer_Changed(Me, EventArgs.Empty)
        _Context.ClearCurrentItem()
    End Sub

    Private Sub EditItem(ByVal isNewItem As Boolean, ByVal customer As CustomerRecord)

        If Not (_newItemInfo Is Nothing) Then
            _Context.ClearCurrentItem()
            _newItemInfo.AbandonItem()
            _newItemInfo = Nothing
        End If

        If isNewItem Then
            CustomerList.SelectedItems.Clear()
            _editItem = Nothing

            Dim msg As IContextMessage = _Context.CreateMessage()
            _newItemInfo = msg.SetNewItem("Customer")
            msg.Commit()
        Else
            _editItem = customer
            Dim msg As IContextMessage = _Context.CreateMessage()
            msg.SetRecordTypeWithId("Customer", customer.Id.ToString())
            msg.SetSuggestedName(customer.SuggestName, customer.Description(FileName))
            msg.Commit()
        End If
        FirstNameTxt.Enabled = True
        LastNameTxt.Enabled = True
        FirstNameTxt.Text = customer.FirstName
        FirstNameTxt.Modified = False
        LastNameTxt.Text = customer.LastName
        LastNameTxt.Modified = False

        If (isNewItem) Then
            CustomerIdTxt.Text = String.Empty
        Else
            CustomerIdTxt.Text = customer.Id
        End If

        RemoveCustomerBtn.Enabled = (isNewItem = False)
        Customer_Changed(Me, EventArgs.Empty)

    End Sub

    Private Sub Customer_Changed(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FirstNameTxt.TextChanged, LastNameTxt.TextChanged, LastNameTxt.KeyUp, FirstNameTxt.KeyUp, LastNameTxt.MouseUp, FirstNameTxt.MouseUp

        RemoveCustomerBtn.Enabled = FirstNameTxt.Enabled

        SaveCustomerBtn.Enabled = Not (String.IsNullOrEmpty(FirstNameTxt.Text) Or String.IsNullOrEmpty(LastNameTxt.Text)) _
                And (FirstNameTxt.Modified Or LastNameTxt.Modified)

    End Sub

    Private Sub CustomerList_ItemSelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ListViewItemSelectionChangedEventArgs) Handles CustomerList.ItemSelectionChanged
        If e.IsSelected Then
            If e.Item Is Nothing Then
                SetNoneItem()
            Else
                SetExistingItem(CType(e.Item, CustomerRecord))
            End If
        Else
            SetNoneItem()
        End If
    End Sub

    Private Sub AddCustomerBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddCustomerBtn.Click
        SetNewItem()
    End Sub

    Private Sub SaveCustomerBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveCustomerBtn.Click

        If _editItem Is Nothing Then

            Dim customer As New CustomerRecord(_nextCustomerId, FirstNameTxt.Text, LastNameTxt.Text)
            _nextCustomerId = _nextCustomerId + 1

            _newItemInfo.SetSuggestedName(customer.SuggestName, customer.Description(FileName))
            _newItemInfo.Commit(customer.Id.ToString())
            _newItemInfo = Nothing

            CustomerList.Items.Add(customer)
            CustomerList.SelectedItems.Clear()
            customer.Selected = True
            EditItem(False, customer)

        Else

            _editItem.FirstName = FirstNameTxt.Text
            FirstNameTxt.Modified = False
            _editItem.LastName = LastNameTxt.Text
            LastNameTxt.Modified = False
            Customer_Changed(Me, EventArgs.Empty)

        End If

    End Sub

    Private Sub RemoveCustomerBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RemoveCustomerBtn.Click
        If _editItem Is Nothing Then
            SetNoneItem()
        Else
            Dim customer As CustomerRecord = _editItem
            customer.Selected = False
            CustomerList.Items.Remove(customer)
            SetNoneItem()
        End If
    End Sub
End Class